//
//  StatusCell.swift
//  weibo1
//
//  Created by changhongliang on 2017/7/26.
//  Copyright © 2017年 richinfo. All rights reserved.
//
/// 在做MVC时需要注意一个思想就时要在模型里面处理好数据,不要在view中处理数据.view中拿到的数据应该是直接可以用的

import UIKit
import SDWebImage
import KILabel
import YYText



enum HLTabelViewCellIdentifier:String {
    case NormalCellIdentifier = "originalCell"
    case ForwardCellIdentifier = "forwardCell"
    static func identifierWithViewModel(viewModel:StatusViewModel) ->String{
        // rawValue 代表获取枚举的原始值
        return (viewModel.status.retweeted_status != nil) ? ForwardCellIdentifier.rawValue : NormalCellIdentifier.rawValue
    }
}

let  StatusPictureCollectionViewCellID = "StatusPictureCollectionViewCellID"



class StatusCell: UITableViewCell {
    
    //用户头像
    var headPortraitImageView: UIImageView?
    //会员图标
    var memberLogo: UIImageView?
    //昵称
    var nicknameLabel: YYLabel?
    //正文
    var contenLabel: YYLabel?
    //来自
    var sourceLabel: YYLabel?
    //时间
    var timeLabel: YYLabel?
    //认证图标
    var authenticationImageView:UIImageView?
    //发布的图片
    var contentImageCollectionView: StatusPictureCollectionView?
    // 转发微博背景
    var forWardBackgroundView: UIView?
    //转发微博正文
    var forWardContentLabel:YYLabel?
    //底部的view
    var bottomView:UIView?
    //转发
    var forwardButton:UIButton?
    //评论
    var commentButton:UIButton?
    //赞
    var likeButton:UIButton?

    
    
    //staus模型
    var statusViewModel: StatusViewModel?{
        didSet{
            //1.设置用户头像
            headPortraitImageView?.sd_setImage(with: statusViewModel?.avatarUrl)
            //2.昵称
            nicknameLabel?.text = statusViewModel?.status.user?.screen_name ?? ""
            //3.时间
            timeLabel?.text = statusViewModel?.createdText ?? ""
            //4.来源
            sourceLabel?.text = statusViewModel?.sourceText ?? ""
            //5.正文
            contenLabel?.text = statusViewModel?.status.text ?? ""
//            contenLabel?.attributedText = KeyboardEmoticonPackage.attributedString(str: statusViewModel?.status.text ?? "", font: (contenLabel?.font)!)
            //认证图标
            authenticationImageView?.image = statusViewModel?.verifiedImage
            //会员图标
            memberLogo?.image = statusViewModel?.mbrankImage
            //转发正文
            if let temp  = statusViewModel?.status.retweeted_status?.text {
                forWardContentLabel?.text = temp
//                forWardContentLabel?.attributedText = KeyboardEmoticonPackage.attributedString(str: temp, font: (forWardContentLabel?.font)!)
            }
            //处理配图
            contentImageCollectionView?.statusViewModel = statusViewModel
            let (itemSize,contentViewSize) = contentImageCollectionView!.caculateSize()
            //设置配图容器的尺寸
            contentImageCollectionView?.snp.updateConstraints { (make) in
                make.width.equalTo(contentViewSize.width)
                make.height.equalTo(contentViewSize.height)

            }

            //设置配图的尺寸
            if  itemSize != CGSize.zero {
                (contentImageCollectionView?.collectionViewLayout as! UICollectionViewFlowLayout).itemSize = itemSize
            }
            //6.4刷新表格
            contentImageCollectionView?.reloadData()
            
            
            
        }
    
    }
    
    
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI(reuseIdentifier: reuseIdentifier)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    func setupUI(reuseIdentifier:String?){
        //添加用户头像
        headPortraitImageView = UIImageView(image:UIImage(named:"avatar_default_big"))
        //设置圆角
//        headPortraitImageView?.layer.cornerRadius = 25
//        headPortraitImageView?.clipsToBounds = true
        self.contentView.addSubview(headPortraitImageView!)
        headPortraitImageView?.snp.makeConstraints({ (make) in
            make.leading.top.equalTo(self.contentView).offset(cellmargin)
            make.width.height.equalTo(avatarHeight)
        })
        
        //添加昵称
        nicknameLabel = YYLabel()
        nicknameLabel?.displaysAsynchronously = true
        nicknameLabel?.font = UIFont.systemFont(ofSize: 17.0)
        self.contentView.addSubview(nicknameLabel!)
        nicknameLabel?.snp.makeConstraints({ (make) in
            make.top.equalTo(headPortraitImageView!)
            make.leading.equalTo(headPortraitImageView!.snp.trailing).offset(10)
        })
        nicknameLabel?.sizeToFit()
        
        //会员头像
        memberLogo = UIImageView(image: UIImage(named:"common_icon_membership_expired"))
        self.contentView.addSubview(memberLogo!)
        memberLogo?.snp.makeConstraints({ (make) in
            make.leading.equalTo(nicknameLabel!.snp.trailing).offset(10)
            make.top.equalTo(nicknameLabel!)
        })
        memberLogo?.sizeToFit()
        
        //认证图标
        authenticationImageView = UIImageView(image:UIImage(named:"avatar_enterprise_vip"))
        self.contentView.addSubview(authenticationImageView!)
        authenticationImageView?.snp.makeConstraints { (make) in
            make.bottom.trailing.equalTo(headPortraitImageView!)
        }
        authenticationImageView?.sizeToFit()
        
        //时间label
        timeLabel = YYLabel()
        timeLabel?.displaysAsynchronously = true
        timeLabel?.textColor = UIColor.orange
        timeLabel?.font = UIFont.systemFont(ofSize: 14.0)
        self.contentView.addSubview(timeLabel!)
        timeLabel?.snp.makeConstraints({ (make) in
            make.leading.equalTo(nicknameLabel!)
            make.bottom.equalTo(headPortraitImageView!)
        })
        
        //fromeLabel
        sourceLabel = YYLabel()
        sourceLabel?.displaysAsynchronously = true
        sourceLabel?.font = UIFont.systemFont(ofSize: 14.0)
        self.contentView.addSubview(sourceLabel!)
        sourceLabel?.snp.makeConstraints({ (make) in
            make.leading.equalTo(timeLabel!.snp.trailing).offset(10.0)
            make.bottom.equalTo(timeLabel!)
        })
        
        //正文
        contenLabel = YYLabel()
        contenLabel?.preferredMaxLayoutWidth = UIScreen.main.bounds.size.width - 20
        contenLabel?.displaysAsynchronously = true
//        contenLabel!.urlLinkTapHandler = { label, url, range in
//                print("发生点击")
//        }
//        contenLabel?.setAttributes([NSForegroundColorAttributeName:UIColor.random], for: KILinkType.URL)
//        contenLabel?.setAttributes([NSForegroundColorAttributeName:UIColor.random], for: KILinkType.hashtag)

//        contenLabel?.font = UIFont(name: "PingFangSC-Regular", size: 17.0)
//        contenLabel?.font = UIFont.systemFont(ofSize: 17.0)
        self.contentView.addSubview(contenLabel!)
        contenLabel?.snp.makeConstraints { (make) in
            make.leading.equalTo(headPortraitImageView!)
            make.width.equalTo(UIScreen.main.bounds.size.width - 20)
            make.top.equalTo(headPortraitImageView!.snp.bottom).offset(10)
        }
        contenLabel?.numberOfLines = 0
//        contenLabel?.sizeToFit()
        
//        contenLabel?.handleURLTap({ (str) in
//            HLLog("labeltest-\(str)")
//        })
        
        //如果是转发的cell
        if reuseIdentifier == "forwardCell" {
            forWardBackgroundView = UIView()
            forWardBackgroundView!.backgroundColor = UIColor.init(red: 245/255.0, green:  245/255.0, blue:  245/255.0, alpha: 1.0)
            contentView.addSubview(forWardBackgroundView!)
            forWardBackgroundView?.snp.makeConstraints({ (make) in
                make.top.equalTo(contenLabel!.snp.bottom).offset(10)
                make.leading.trailing.equalToSuperview()
            })
            
            //添加转发微博的正文
//            forWardContentLabel = KILabel()
            forWardContentLabel = YYLabel()
            forWardContentLabel?.preferredMaxLayoutWidth = UIScreen.main.bounds.size.width - 20
            forWardContentLabel?.displaysAsynchronously = true
//            forWardContentLabel?.setAttributes([NSForegroundColorAttributeName:UIColor.random], for: KILinkType.URL)
//             forWardContentLabel?.setAttributes([NSForegroundColorAttributeName:UIColor.random], for: KILinkType.hashtag)
//            forWardContentLabel?.urlLinkTapHandler = { label, url, range in
//                print("发生点击")
//            }
            forWardContentLabel?.font = UIFont.systemFont(ofSize: 17.0)
            forWardContentLabel?.numberOfLines = 0
            forWardBackgroundView?.addSubview(forWardContentLabel!)
            forWardContentLabel?.snp.makeConstraints({ (make) in
                make.leading.top.equalTo(forWardBackgroundView!).offset(10)
                make.width.equalTo(UIScreen.main.bounds.size.width - 20)
            })
            forWardContentLabel?.sizeToFit()
            
            //微博图片
            contentImageCollectionView = StatusPictureCollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout())
            contentImageCollectionView?.backgroundColor = UIColor.clear
            forWardBackgroundView?.addSubview(contentImageCollectionView!)
             contentImageCollectionView?.snp.makeConstraints({ (make) in
                make.leading.equalTo(forWardContentLabel!)
                make.top.equalTo(forWardContentLabel!.snp.bottom).offset(10)
                make.bottom.equalTo(forWardBackgroundView!).offset(-10)
                make.width.height.equalTo(0)
            })
  
            
        }else {
            //微博图片
            contentImageCollectionView = StatusPictureCollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout())
            contentImageCollectionView?.backgroundColor = UIColor.clear
            self.contentView.addSubview(contentImageCollectionView!)
            contentImageCollectionView?.snp.makeConstraints({ (make) in
                make.leading.equalTo(headPortraitImageView!)
                make.top.equalTo(contenLabel!.snp.bottom).offset(10)
                make.width.height.equalTo(0)
            })
        }
        contentImageCollectionView?.dataSource = self
        contentImageCollectionView?.delegate = self
        //注册contViewCell 
        contentImageCollectionView?.register(StatusPictureCollectionViewCell.classForCoder(), forCellWithReuseIdentifier: StatusPictureCollectionViewCellID)
        //底部view
        bottomView = UIView()
//        bottomView?.backgroundColor = UIColor.green
        let referenceView = reuseIdentifier == "forwardCell" ? forWardBackgroundView! : contentImageCollectionView!
//        referenceView.backgroundColor = UIColor.red
        self.contentView.addSubview(bottomView!)
        bottomView?.snp.makeConstraints({ (make) in
            make.top.equalTo(referenceView.snp.bottom).offset(10)
            make.leading.trailing.equalTo(self.contentView)
            make.height.equalTo(44)
            
        })
        //转发
        forwardButton = BottomButton()
        forwardButton?.setImage(UIImage(named:"timeline_icon_retweet"), for:.normal)
        forwardButton?.setTitle("转发", for: .normal)
        bottomView?.addSubview(forwardButton!)
        
        forwardButton?.snp.makeConstraints({ (make) in
            make.leading.bottom.top.equalTo(bottomView!)
        })

        
        //评论
        commentButton = BottomButton()
        commentButton?.setImage(UIImage(named:"timeline_icon_comment"), for: .normal)
        commentButton?.setTitle("评论", for: .normal)
        bottomView?.addSubview(commentButton!)
        
       
        commentButton?.snp.makeConstraints { (make) in
            make.left.equalTo(forwardButton!.snp.right)
            make.top.bottom.equalTo(bottomView!)
            make.width.equalTo(forwardButton!)
        }
        
        //点赞
        likeButton = BottomButton()
        likeButton?.setTitle("点赞", for: .normal)
        likeButton?.setImage(UIImage(named:"timeline_icon_unlike"), for: .normal)
        bottomView?.addSubview(likeButton!)
        likeButton!.snp.makeConstraints { (make) in
            make.left.equalTo(commentButton!.snp.right)
            make.top.bottom.trailing.equalTo(bottomView!)
            make.width.equalTo(commentButton!)
        }
        
    }
    
    
    ///MARK: - 计算行高
    func caculateRowHeight(status:StatusViewModel) -> CGFloat {
        // 1.将数据赋值给当前的cell
        self.statusViewModel = status
        //2.更新UI
        layoutIfNeeded()
        //3.返回行高
//         return contenLabel!.frame.maxY + 44
        return bottomView!.frame.origin.y + 44
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
      self.next?.touchesBegan(touches, with: event)
    }

    
        
}


//微博图片



